import { creatProxy, ProxyTypes } from "../../rstore-react-ts";
import {
  Table,
  Button,
  Modal,
  Form,
  Input,
  Switch,
  Select,
  message,
} from "antd";
import request from "../../api";
import { useState, useEffect } from "react";
import { cloneDeep } from "lodash";
const {
  reqUserData,
  reqRoule,
  reqRegions,
  reqAddUser,
  reqDelUser,
  reqChangeUser,
  reqChangeUserData,
} = request;
const { confirm } = Modal;
type userList = Array<{
  username: string;
  password: number;
  roleState: boolean;
  default: boolean;
  region: string;
  roleId: number;
  id: number;
}>;
type rouleType = Array<{
  id: number;
  roleName: string;
  roleType: number;
  rights: Array<string>;
}>;
type regionsType = Array<{
  id: number;
  title: string;
  value: string;
}>;
interface inputData {
  id?: number;
  username?: string;
  password?: string;
  roleState: boolean;
  default: false;
  region: string;
  roleId?: number;
}
const Role = (props: ProxyTypes) => {
  const {
    actions,
    data: { global },
  } = props.rStatus;
  const id = Number(localStorage.getItem("token"));
  const [isModalVisible, useIsModalVisible] = useState<boolean>(false);
  const [roule, useRoule] = useState<rouleType>([]);
  const [regions, useRegions] = useState<regionsType>([]);
  const [from] = Form.useForm();
  const [topper, useTopper] = useState<boolean>(false);
  const [userList, useUserList] = useState<userList>([]);
  const [inputData, useInputData] = useState<inputData>({
    default: false,
    region: "",
    roleState: true,
  });
  const onFinish = async (e: any) => {
    const data = { ...inputData, ...e, roleId: Number(e.roleId) };
    if (inputData.id) {
      await reqChangeUserData(inputData.id, data);
    } else {
      await reqAddUser(data);
    }
    await getUserData();
    from.resetFields();
    message.success("添加成功");
    useInputData({
      default: false,
      region: "",
      roleState: true,
    });
    useIsModalVisible(false);
  };
  const getRoule = async () => {
    const result = (await reqRoule()) as unknown as rouleType;
    useRoule(id === 1 ? result : result.filter((item) => item.id > id));
  };
  const getRegions = async () => {
    const result = (await reqRegions()) as unknown as regionsType;
    useRegions(
      id === 1
        ? result
        : result.filter((item) => item.title === global.userRegion)
    );
  };

  useEffect(() => {
    actions.global.changeTitel("用户管理");
    getUserData();
    getRegions();
    getRoule();
  }, []);
  const getUserData = async () => {
    const result = (await reqUserData()) as unknown as userList;
    useUserList(
      id === 1
        ? result
        : result.filter((Item) => {
            return Item.roleId > id && Item.region === global.userRegion;
          })
    );
  };
  const switchKey = (item: number) => {
    switch (item) {
      case 1:
        return "超级管理员";
      case 2:
        return "区域管理员";
      case 3:
        return "区域编辑";
    }
  };
  const columns = [
    {
      title: "区域",
      dataIndex: "region",
      keys: "region",
      render: (item: string) => {
        if (item === "") {
          return <>全球</>;
        }
        return <>{item}</>;
      },
    },
    {
      title: "角色名称",
      dataIndex: "roleId",
      keys: "roleId",
      render: (item: number) => {
        return switchKey(item);
      },
    },
    {
      title: "用户名",
      dataIndex: "username",
      keys: "username",
    },
    {
      title: "用户状态",
      dataIndex: "roleState",
      keys: "roleState",
      render: (_: boolean, item: any) => {
        return (
          <>
            <Switch
              checked={item.roleState}
              disabled={item.default}
              onClick={async () => {
                await reqChangeUser(item.id, !item.roleState);
                await getUserData();
              }}
            />
          </>
        );
      },
    },
    {
      title: "操作",
      keys: "button",
      render: (item: any) => {
        return (
          <>
            <Button
              danger
              style={{ margin: "0 10px" }}
              disabled={item.default}
              onClick={() => {
                confirm({
                  title: "确定删除吗",
                  cancelText: "取消",
                  okText: "确定",
                  onOk: async () => {
                    await reqDelUser(item.id);
                    await getUserData();
                    message.success("已删除");
                  },
                });
              }}
            >
              删除
            </Button>
            <Button
              type="primary"
              disabled={item.default}
              onClick={() => {
                useInputData({
                  ...inputData,
                  id: item.id,
                });
                from.setFieldsValue({
                  ...cloneDeep(item),
                  roleId: switchKey(item.roleId),
                });
                useIsModalVisible(true);
              }}
            >
              编辑
            </Button>
          </>
        );
      },
    },
  ];

  return (
    <>
      <Modal
        visible={isModalVisible}
        onCancel={() => {
          from.resetFields();
          useIsModalVisible(false);
          useTopper(false);
        }}
        footer={[
          <Button key="back" onClick={() => useIsModalVisible(false)}>
            完成
          </Button>,
        ]}
      >
        <Form
          name="basic"
          form={from}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 24 }}
          initialValues={inputData}
          onFinish={onFinish}
          autoComplete="off"
          labelWrap
          layout="vertical"
        >
          <Form.Item
            label="账号"
            name="username"
            rules={[
              {
                required: true,
                message: "名称是必填的",
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="密码"
            name="password"
            rules={[
              {
                required: true,
                message: "密码是必填的",
              },
            ]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item
            label="区域"
            name="region"
            rules={
              topper
                ? []
                : [
                    {
                      required: true,
                      message: "角色是必选项",
                    },
                  ]
            }
          >
            <Select disabled={topper || regions.length <= 1}>
              {regions.map((item) => {
                return (
                  <Select.Option key={item.value}>{item.value}</Select.Option>
                );
              })}
            </Select>
          </Form.Item>
          <Form.Item
            label="角色"
            name="roleId"
            rules={[
              {
                required: true,
                message: "角色是必选项",
              },
            ]}
          >
            <Select
              disabled={roule.length <= 1}
              onChange={(e) => {
                if (e === "1") {
                  useTopper(true);
                  from.setFieldsValue({
                    ...from.getFieldsValue(true),
                    region: "",
                  });
                } else {
                  useTopper(false);
                }
                from.validateFields();
              }}
            >
              {roule.map((item) => {
                return (
                  <Select.Option key={item.id}>
                    {switchKey(item.id)}
                  </Select.Option>
                );
              })}
            </Select>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 10, span: 12 }}>
            <Button type="primary" htmlType="submit">
              保存
            </Button>
          </Form.Item>
        </Form>
      </Modal>
      <Button
        type="primary"
        onClick={() => {
          from.setFieldsValue({
            username: "",
            password: "",
            region: regions[0].title,
            roleId: roule[0].roleName,
          });
          useIsModalVisible(true);
        }}
      >
        添加用户
      </Button>
      <Table
        dataSource={userList}
        columns={columns}
        rowKey="id"
        pagination={{
          pageSize: 5,
        }}
      />
      ;
    </>
  );
};

export default creatProxy(Role, ["global"]);
